package com.demo.test;


import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.CharEncoding;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 延时队列 需要安装延时队列的插件
 */
@RequestMapping("delay")
@Controller
@Slf4j
public class YSScheduleController {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Value("${deadLetter.normal.exchange}")
    private String topicExchange;


    /**
     * 测试正常消息异常 到达死信队列
     */
   @GetMapping("/test1")
    public void sendEmailMessage() {

        String msg = RandomStringUtils.randomAlphanumeric(8);
        JSONObject email=new JSONObject();
        email.put("content",msg);
        email.put("to","duchong@qq.com");
        CorrelationData correlationData=new CorrelationData("123456");

        rabbitTemplate.convertAndSend("delayNormalTopicExchange","delayNormalQueueRoutingKey.x",
                email.toJSONString(),correlationData);
        log.info("---发送 email 消息---{}---messageId---{}",email,correlationData.getId());
    }

    /**
     * 测试延时消息
     * @throws Exception
     */
    @GetMapping("/test2")
    public void sendDelayOrderMessage() throws Exception{

        //订单号 id实际是保存订单后返回的，这里用uuid代替
        String orderId = UUID.randomUUID().toString();
        // 模拟订单信息
        JSONObject order=new JSONObject();
        order.put("orderId",orderId);
        order.put("goodsName","vip充值");
        order.put("orderAmount","99.00");
        CorrelationData correlationData=new CorrelationData(orderId);// 自定义业务标识
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setMessageId(orderId);
        //30分钟时间太长，这里延时120s消费
        messageProperties.setHeader("x-delay", 5000);
        Message message = new Message(order.toJSONString().getBytes(CharEncoding.UTF_8), messageProperties);

        rabbitTemplate.convertAndSend(topicExchange,"delayQueueRoutingKey.x",message,correlationData);

        log.info("---发送 order 消息---{}---orderId---{}",order,correlationData.getId());
        //睡一会，为了看延迟效果
        TimeUnit.MINUTES.sleep(10);
    }

}
